import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getLoginType, getIsLogin, getToken } from '@/utils/auth'
NProgress.configure({ showSpinner: false })

const whiteList = ['/user/login']

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const hasLogin = getToken()
  if (to.path.indexOf('web') === -1) {
    store.dispatch('app/setVisitTemplate', 'admin')
  }else {
    
    store.dispatch('app/setVisitTemplate', 'web')
  }
  if (hasLogin && getIsLogin()) {
    if (to.path === '/user/login') {
      store.dispatch('app/setVisitTemplate', 'web')
      next({ path: '/web'})
      NProgress.done()
    } else {
      const set_router = store.getters.name
      if (set_router) {
        if (to.path === '/') {
          next({path: '/admin'})
        } else {
          next()
        }
        
      } else {
        try {
          const { roles } = await store.dispatch('user/getUserInfo') 
          const accessRoutes = await store.dispatch('generateRoutes',getLoginType())
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          // await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/user/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/user/login?redirect=${to.path}`)
      NProgress.done()
    }
  } 
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})